package job.job_0820;

public class Recurrence {
    public static void main(String[] args) {
        System.out.println(sumAdd(1234));
        sequentialPrinting(1234);
        System.out.println();
        System.out.println(sum(10));
        System.out.println(factor(4));
        System.out.println(fibo(4));
        System.out.println(fibo1(4));

    }
    public static int fibo(int n) {//斐波那契数
        if(n<3)
            return 1;
        return fibo(n-1)+fibo(n-2);
    }
    public static int fibo1(int n){//斐波那契数
        int last1=1;
        int last2=1;
        int cur=0;
        for(int i=3;i<=n;i++){
            cur=last1+last2;
            last1=last2;
            last2=cur;
        }
        return cur;
    }
    public static int factor(int n){//递归求 N 的阶乘
        if(n<=2)
            return n;
        return n*factor(n-1);
    }
    public static int sum(int n){//递归求 1 + 2 + 3 + ... + 10
        if(n<2)
            return n;
        return n+sum(n-1);
    }
    public static void sequentialPrinting(int n){//按顺序打印一个数字的每一位(例如 1234 打印出 1 2 3 4) （递归）
        if(n<10) {
            System.out.print(n + " ");
            return;
        }
        sequentialPrinting(n/10);
        System.out.print(n%10+" ");
    }
    public static int sumAdd(int n){//写一个递归方法，输入一个非负整数，返回组成它的数字之和
        if(n<10)
            return n;
        return n%10+sumAdd(n/10);
    }

}
